<?php
/************************
KVDB不兼容，初始化暂停。
************************/
/*
$kv = new SaeKV();
$ret = $kv->init();
*/

function autoLink($content) {
	$content = preg_replace('/(http:\/\/(t.cn\/[a-zA-Z0-9]+))/', '<a target="_blank" rel="nofollow" href="${1}">${2}</a> <a href="javascript:;" style="font-size: 20px" onclick="showqr(\'${1}\');return false;">▣</a>', $content);
	$content = preg_replace('/#([^#]+)#/', '<a href="/trend/${1}">#${1}#</a>', $content);
	return $content;
}

function autoMention($content){
	$content = preg_replace('/@(([a-zA-Z0-9\-_一-龥])+)/', '<a class="mentionLinks" href="/user/${1}">@${1}</a>', $content);
	return $content;
}

function exFace($content){
	$facelist = getFaces();
	$content = str_replace($facelist["search"],$facelist["replace"],$content);
	return $content;
}

/*****************************************
getFaces函数，用于获取表情列表，memcache
不兼容待改写，函数暂时保留位置。
*****************************************/
function getFaces(){
	/*
	global $c;
	if(!($facecn = getCookieCache('facelistcn', 1))){
		$facecn = $c->emotions("face", "cnname");
		$facecn = json_encode($facecn);
		setCache('facelistcn', $facecn, 1);
	}
	if(!($facetw = getCookieCache('facelisttw', 1))){
		$facetw = $c->emotions("face", "twname");
		$facetw = json_encode($facetw);
		setCache('facelisttw', $facetw, 1);
	}
	$facelist = array_merge( $facecn, $facetw );
	$facelist["search"] = array();
	$facelist["replace"] = array();
	for($i=0; $i<count($facelist); $i++){
		array_push($facelist["search"], $facelist[$i]["phrase"]);
		array_push($facelist["replace"], "<img style='max-height: 14px;' src='".($_SERVER['HTTPS']?"/qsimg/".base64_encode($facelist[$i]["url"]):$facelist[$i]["url"])."' />");
	}
	return $facelist;
	*/
}

function format($content){
	$fd = 0;
	$content = str_replace("＃", "#", $content);
	for($i=0; $i<count($keywords); $i++){
		if(strpos($content, $keywords[$i]) !== false){
			$fd = 1;
			break;
		}
	}
	return exFace(autoMention(autoLink(htmlspecialchars($content))));
}

/*****************************************
checkDB函数，用于检测微博是否已缓存，KVDB
不兼容待改写，函数暂时保留位置。
*****************************************/
function checkDB($id){
	return false;
	/*
	global $kv;
	if($kv->get($id)){
		return false;
	}
	else{
		return true;
	}
	*/
}

/*****************************************
saveDB函数，用于保存微博缓存状态，KVDB不兼
容待改写，函数暂时保留位置。
*****************************************/
function saveDB($id, $created_at, $text, $source, $thumbnail_pic=NULL, $bmiddle_pic=NULL, $original_pic=NULL, $user, $retweeted_status=NULL){
	return false;
	/*
	$conn = mysql_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS);
	$db = mysql_select_db(SAE_MYSQL_DB);
	$sql = "INSERT INTO `statuses`(`id`,`created_at`,`text`,`source`,`thumbnail_pic`,`bmiddle_pic`,`original_pic`,`user`,`retweeted_status`) values('$id','$created_at','$text','$source','$thumbnail_pic','$bmiddle_pic','$original_pic','$user','$retweeted_status');";
	$result = mysql_query($sql);
	mysql_close($conn);
	global $kv;
	$kv->add($id, 1);
	*/
}

/*****************************************
cacheWeibo函数，用于保存微博缓存，KVDB不兼
容，待改写，函数暂时保留位置。
*****************************************/
function cacheWeibo($statues){
	return false;
	/*
	$id = $statues["id"];
	$created_at = $statues["created_at"];
	$text = $statues["text"];
	$source = $statues["source"];
	$thumbnail_pic = $statues["thumbnail_pic"];
	$bmiddle_pic = $statues["bmiddle_pic"];
	$original_pic = $statues["original_pic"];
	$user = $statues["user"]["id"];
	$retweeted_status = $statues["retweeted_status"]["id"];
	if(checkDB($id)){
		saveDB($id, $created_at, $text, $source, $thumbnail_pic, $bmiddle_pic, $original_pic, $user, $retweeted_status);
		return true;
	}
	else{
		return false;
	}
	*/
}

/*****************************************
getCache函数，用于获取微博缓存，KVDB不兼容
待改写，函数暂时保留位置。
*****************************************/
function getCache($id){
	return false;
	/*
	global $c;
	if(checkDB($id)){
		return false;
	}
	else{
		$conn = mysql_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS);
		$db = mysql_select_db(SAE_MYSQL_DB);
		$sql = "SELECT * FROM `statuses` WHERE `id`='$id' LIMIT 1;";
		$result = mysql_query($sql);
		$statues = mysql_fetch_array($result);
		mysql_close($conn);
		$statues["user"] = $c->show_user_by_id($statues["user"]);
		if($statues["retweeted_status"]){
			$retweeted_status = $c->show_status($statues["retweeted_status"]);
		}
		else{
			$retweeted_status = NULL;
		}
		if($retweeted_status && !$retweeted_status["user"]["screen_name"]){
			$statues["retweeted_status"] = getCache($statues["retweeted_status"]);
		}
		else{
			$statues["retweeted_status"] = $retweeted_status;
		}
		return $statues;
	}
	*/
}

/*****************************************
checkUser函数，用于检测用户是否首次登陆，
MySQL配置不兼容，待改写，函数暂时保留位置。
*****************************************/
function checkUser($id){
	return false;
	/*
	$conn = mysql_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS);
	$db = mysql_select_db(SAE_MYSQL_DB);
	$sql = "SELECT COUNT(*) AS `row` FROM `users` WHERE id='$id' LIMIT 1;";
	$result = mysql_query($sql);
	$out = mysql_fetch_array($result);
	mysql_close($conn);
	if($out["row"]){
		return false;
	}
	else{
		return true;
	}
	*/
}

/*****************************************
saveUser函数，用于保存用户访问记录，MySQL配
置不兼容，待改写，函数暂时保留位置。
*****************************************/
function saveUser($id){
	return false;
	/*
	$conn = mysql_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS);
	$db = mysql_select_db(SAE_MYSQL_DB);
	$sql = "INSERT INTO `users`(`id`) values('$id');";
	$result = mysql_query($sql);
	mysql_close($conn);
	*/
}

function register($id){
	if(checkUser($id)){
		saveUser($id);
		return true;
	}
	else{
		return false;
	}
}

function getVideoUrl($content){
	preg_match_all('/http:\/\/t.cn\/([a-zA-Z0-9]+)/', $content, $urls);
	if(count($urls[1])<1){
		return NULL;
	}
	$url = "http://api.t.sina.com.cn/short_url/batch_info.json?source=3680077589&url_short=".implode(",", $urls[1]);
	$r = file_get_contents($url);
	$r = json_decode($r, true);
	for($i=0; $i<count($r); $i++){
		if($r[$i]["type"]==1){
			return array($r[$i]["annotations"][0]["url"], $r[$i]["annotations"][0]["title"]);
		}
	}
	return NULL;
}

function getMusicUrl($content){
	preg_match_all('/http:\/\/t.cn\/([a-zA-Z0-9]+)/', $content, $urls);
	if(count($urls[1])<1){
		return NULL;
	}
	$url = "http://api.t.sina.com.cn/short_url/batch_info.json?source=3680077589&url_short=".implode(",", $urls[1]);
	$r = file_get_contents($url);
	$r = json_decode($r, true);
	for($i=0; $i<count($r); $i++){
		if($r[$i]["type"]==2){
			$thisUrl = $r[$i]["url_long"];
			preg_match('/http:\/\/www.xiami.com\/song\/([0-9]+)/', $thisUrl, $musicUrl);
			if($musicUrl[1]){
				return "http://www.xiami.com/widget/0_".$musicUrl[1]."/singlePlayer.swf";
			}
		}
	}
	return NULL;
}

/*****************************************
searchTimeline函数，用于搜索缓存微博，MySQL
配置不兼容，待改写，函数暂时保留位置。
*****************************************/
function searchTimeline($q, $count=10, $page=1, $max_id=0){
	return false;
	/*
	global $c;
	if(!$q){
		return false;
	}
	$q = urldecode($q);
	if(substr($q,0,7)=="base64:"){
		$q = base64_decode(substr($q,7));
	}
	if($count<=0 || $count>200){
		$count = 10;
	}
	if($page<=0){
		$page = 1;
	}
	$start = $count*($page-1);
	$ids = array();
	$conn = mysql_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS);
	$db = mysql_select_db(SAE_MYSQL_DB);
	if(substr($q,0,7)=="source:"){
		$q = substr($q,7);
		if($max_id){
			$sql = "SELECT * FROM `statuses` WHERE MATCH (`source`) AGAINST ('$q') AND `id`<='$max_id' ORDER BY `id` DESC LIMIT $start,$count;";
		}
		else{
			$sql = "SELECT * FROM `statuses` WHERE MATCH (`source`) AGAINST ('$q') ORDER BY `id` DESC LIMIT $start,$count;";
		}
	}
	else if(substr($q,0,5)=="user:"){
		$q = substr($q,5);
		$userMessage = $c->show_user_by_name($q);
		if(!$userMessage["error_code"]){
			$q = $userMessage["id"];
		}
		if($max_id){
			$sql = "SELECT * FROM `statuses` WHERE `user`='$q' AND `id`<='$max_id' ORDER BY `id` DESC LIMIT $start,$count;";
		}
		else{
			$sql = "SELECT * FROM `statuses` WHERE `user`='$q' ORDER BY `id` DESC LIMIT $start,$count;";
		}
	}
	else if(substr($q,0,4)=="uid:"){
		$q = substr($q,4);
		if($max_id){
			$sql = "SELECT * FROM `statuses` WHERE `user`='$q' AND `id`<='$max_id' ORDER BY `id` DESC LIMIT $start,$count;";
		}
		else{
			$sql = "SELECT * FROM `statuses` WHERE `user`='$q' ORDER BY `id` DESC LIMIT $start,$count;";
		}
	}
	else if(substr($q,0,1)=="$"){
		$q = substr($q,1);
		if($max_id){
			$sql = "SELECT * FROM `statuses` WHERE `id`<='$max_id' AND `text` LIKE '%$q%' ORDER BY `id` DESC LIMIT $start,$count;";
		}
		else{
			$sql = "SELECT * FROM `statuses` WHERE `text` LIKE '%$q%' ORDER BY `id` DESC LIMIT $start,$count;";
		}
	}
	else{
		if($max_id){
			$sql = "SELECT * FROM `statuses` WHERE MATCH (`text`) AGAINST ('$q') AND `id`<='$max_id' ORDER BY `id` DESC LIMIT $start,$count;";
		}
		else{
			$sql = "SELECT * FROM `statuses` WHERE MATCH (`text`) AGAINST ('$q') ORDER BY `id` DESC LIMIT $start,$count;";
		}
	}
	$result = mysql_query($sql);
	$timeline = array();
	if(isset($_GET["cache"])){
		$userMessage = $c->show_user_by_name($q);
		if($userMessage["error_code"]){
			$userMessage = $c->show_user_by_id($q);
		}
		if($q=='1220291284'){
			$userMessage = array();
			$userMessage["id"] = 1220291284;
			$userMessage["idstr"] = "1220291284";
			$userMessage["screen_name"] = "作业本";
			$userMessage["name"] = "作业本";
			$userMessage["profile_image_url"] = "http://qingshuang.sinaapp.com/images/zyb.jpg";
		}
	}
	while($out = mysql_fetch_array($result)){
		array_push($ids, $out["id"]);
		if(isset($_GET["cache"])){
			$out["user"] = $userMessage;
			$out["retweeted_status"] = getCache($out["retweeted_status"]);
			array_push($timeline, $out);
		}
	}
	mysql_close($conn);
	if(isset($_GET["cache"])){
		return $timeline;
	}
	$timeline = $c->show_batch(join(",",$ids));
	return $timeline["statuses"];
	*/
}

function formatTime($time){
	if(date("Ymd") - date("Ymd",strtotime($time)) == 1){
		return "昨天 ".date("H:i",strtotime($time));
	}
	else if(date("Ymd") - date("Ymd",strtotime($time)) == 0){
		if(date("His") - date("His",strtotime($time)) < 59){
			return (date("His") - date("His",strtotime($time)))."秒前";
		}
		else if(date("Hi") - date("Hi",strtotime($time)) < 59){
			return (date("Hi") - date("Hi",strtotime($time)))."分钟前";
		}
		else{
			return "今天 ".date("H:i",strtotime($time));
		}
	}
	else if(date("Y") != date("Y",strtotime($time))){
		return date("Y-m-d H:i",strtotime($time));
	}
	else{
		return date("m-d H:i",strtotime($time));
	}
}

function getBase64Image($imageData){
	$imageData = trim($imageData);
	$filteredData = substr($imageData, strpos($imageData, ",")+1);
	$unencodedData = base64_decode($filteredData);
	$s = new SaeStorage();
	$filename = strtotime("now");
	$filename = md5($filename);
	$filename = $filename.".png";
	$url = $s->write("cache","images/".$filename,$unencodedData);
	if($url){
		return $url;
	}
}

/*****************************************
getCookieCache函数，用于获取头像cookie session，
memcache不兼容，待改写，函数暂时保留位置。
*****************************************/
function getCookieCache($key, $f){
	return false;
	/*
	if($f){
		$key = $_COOKIE['f_session']."_".$key;
	}
	else{
		$key = $_COOKIE['q_session']."_".$key;
	}
	$mmc = memcache_init();
	$cookieCache = memcache_get($mmc, $key);
	if( $cookieCache ){
		try{
			$cookieCache = json_decode($cookieCache, true);
			return $cookieCache;
		}
		catch(Exception $e){
			return false;
		}
	}
	else{
		return false;
	}
	*/
}

/*****************************************
setCache函数，用于缓存表情，memcache不兼容
待改写，函数暂时保留位置。
*****************************************/
function setCache($key, $value, $f){
	return false;
	/*
	if($f){
		$key = $_COOKIE['f_session']."_".$key;
	}
	else{
		$key = $_COOKIE['q_session']."_".$key;
	}
	$mmc = memcache_init();
	memcache_set($mmc, $key, $value);
	*/
}

/*****************************************
isGhost函数，用于判断僵尸用户，MySQL配置不、
兼容，待改写，函数暂时保留位置。
*****************************************/
function isGhost($user){
	return false;
	/*
	$lifetime = strtotime("now") - strtotime($user["created_at"]);
	$followerscount = $user["followers_count"];
	$friendscount = $user["friends_count"];
	$statusescount = $user["statuses_count"];
	$bifollowerscount = $user["bi_followers_count"];
	$recentstatustime = strtotime("now") - strtotime(getStatusTime($user["status_id"]));
	if($lifetime <= 7*24*3600){
		if($statusescount < 1 || $bifollowerscount/$followerscount>0.8 && $followerscount>=50 || $statusescount >= 50){
			return true;
		}
		else{
			return false;
		}
	}
	else if($lifetime <= 30*24*3600){
		if($statusescount < 1 || $bifollowerscount/$followerscount>0.8 && $followerscount>=50 || $bifollowerscount<5){
			return true;
		}
		else{
			return false;
		}
	}
	else if($lifetime <= 3*30*24*3600){
		if($statusescount < 1 || $bifollowerscount<5){
			return true;
		}
		else{
			return false;
		}
	}
	else if($recentstatustime >= 2*30*24*3600){	//have no new status in two months at lest
		return true;
	}
	else{
		return false;
	}
	*/
}

/*****************************************
getStatusTime函数，用于获取用户被缓存的最后
一条微博的时间，MySQL配置不兼容，待改写，函
数暂时保留位置。
*****************************************/
function getStatusTime($id){
	return false;
	/*
	$conn = mysql_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS);
	$db = mysql_select_db(SAE_MYSQL_DB);
	$sql = "SELECT * FROM  `statuses` WHERE  `id` <=  '$id' ORDER BY  `id` DESC LIMIT 0 , 1";
	$result = mysql_query($sql);
	$out = mysql_fetch_array($result);
	mysql_close($conn);
	return $out["created_at"];
	*/
}

/*****************************************
saveToken函数，用于保存用户授权凭证，MySQL
配置不兼容，待改写，函数暂时保留位置。
*****************************************/
function saveToken($uid, $token){
	return false;
	/*
	if(!$uid || !$token){
		return null;
	}
	setcookie("uid", $uid, time()+3600*24*365*2);
	setcookie("access_token", strtoupper(md5($uid.strtoupper(md5($token['access_token'])))), time()+3600*24*365*2);
	setcookie("token", 0, time()-3600*24*365*2);
	$token = json_encode($token);
	$conn = mysql_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS);
	$db = mysql_select_db(SAE_MYSQL_DB);
	$sql = "UPDATE `users` SET `access_token` = '$token' WHERE `id` = '$uid'";
	$result = mysql_query($sql);
	*/
}

/*****************************************
getToken函数，用于获取用户授权凭证，MySQL
配置不兼容，待改写，函数暂时保留位置。
*****************************************/
function getToken(){
	return false;
	/*
	setcookie("token", 1);
	if(!$_COOKIE['access_token']){
		return false;
	}
	$uid = $_COOKIE['uid'];
	if(!$uid){
		return null;
	}
	$conn = mysql_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS);
	$db = mysql_select_db(SAE_MYSQL_DB);
	$sql = "SELECT * FROM  `users` WHERE  `id` = '$uid' LIMIT 0 , 1";
	$result = mysql_query($sql);
	$out = mysql_fetch_array($result);
	mysql_close($conn);
	$token = json_decode($out["access_token"], true);
	if($_COOKIE['access_token'] == strtoupper(md5($uid.strtoupper(md5($token['access_token']))))){
		$_SESSION['token'] = $token;
	}
	else{
		return false;
	}
	*/
}
?>